// 实现对路况报告Road_Condition_Report表的增改查
const { Road_Condition_Report } = require('../model/create_tables')
const { Op } = require('sequelize')

/* 新增路况报告 */
const addReport = async (reportObj) => {
  const res = await Road_Condition_Report.create(reportObj)
  return {
    status: 1,
    message: '新增路况报告成功',
    data: res.toJSON(),
  }
}

/* 查询路况报告 */
// 根据id查询路况报告
const getReportById = async (id) => {
  const res = await Road_Condition_Report.findByPk(id)
  return res
    ? { status: 1, message: '获取报告成功', data: res.toJSON() }
    : { status: 0, message: '未找到相关报告' }
}

// 模糊查询路况报告
const getReport = async (str) => {
  const where = {}
  if (str?.trim()) {
    where[Op.or] = [
      { eventType: { [Op.like]: `%${str}%` } },
      { eventAddress: { [Op.like]: `%${str}%` } },
      { nearbyBuilding: { [Op.like]: `%${str}%` } },
      { eventDescription: { [Op.like]: `%${str}%` } },
    ]
  }
  const res = await Road_Condition_Report.findAll({ where })

  if (res.length >= 2) {
    return {
      message: '找到多个路况报告',
      data: res.map((report) => report.toJSON()),
      status: 1,
    }
  } else if (res.length == 1) {
    return {
      message: '找到一个路况报告',
      data: res[0].toJSON(),
      status: 1,
    }
  } else {
    return {
      message: '未找到相关路况报告',
      status: 0,
    }
  }
}

/* 更新路况报告 */
// 根据id更新路况报告审核状态
const updateReportStatus = async (id, status) => {
  // 先根据id查找路况报告
  const report = await Road_Condition_Report.findByPk(id)
  if (!report) {
    return {
      message: '未找到该路况报告，修改失败',
      status: 0,
    }
  }
  // 更新审核状态
  const res = await Road_Condition_Report.update(
    { auditStatus: status },
    {
      where: {
        id,
      },
    }
  )
  if (res[0] === 1) {
    return {
      message: '修改成功',
      status: 1,
    }
  } else {
    return {
      message: '修改失败',
      status: 0,
    }
  }
}

exports.addReport = addReport
exports.getReportById = getReportById
exports.getReport = getReport
exports.updateReportStatus = updateReportStatus
